<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-11-15 10:51
 *
 * 项目：rm  -  $  - fieldValidations.php
 *
 * 作者：liwei 
 */

namespace modules\levfm\table\form\FormData;

use Lev;
use lev\helpers\UrlHelper;
use modules\levfm\table\LevfmDatas;
use modules\levfm\table\LevfmFields;
use modules\levfm\widgets\inputs\inputsFormWidget;

!defined('INLEV') && exit('Access Denied LEV');


class fieldValidations
{
    public static $errorMsg = [];
    public static $opInfo = [];
    public static $inputInfo = [];

    /**
     * @see fieldValidations::rule_must()
     */
    public static $ruleSettings = [
        'must'      => '抱歉，有必填项未填写',
        'minLen'    => '抱歉，填少了，有未达到最低填写标准项',
        'maxLen'    => '抱歉，填多了，有超出最大填写项',
        'unique'    => '抱歉，有项填写已经存在相同值',
        'include'   => '抱歉，有项填写包含禁止关键词',
        //'rule_dataType',
    ];

    /**
     * @see fieldValidations::dataType()
     */
    public static $dataTypes = [
        '0'         => '字串',
        'floatval'  => '浮点数（小数）',
        'intval'    => '整数',
        'url'       => '网址',
        'email'     => '邮箱',
        'mobile'    => '中国大陆手机号',
        'ip'        => 'IPv4',
        'ipv6'      => 'IPv6',
        'letter'    => '字母',
        'letters'   => '字母和数字',
        'letters2'  => '只允许字母、数字和下划线，必须以字母开头',
        'letters3'  => '只允许字母、数字、中划线和下划线，不允许点【.】开头',
    ];

    /**
     * @param $valiData
     * @param array $inputInfo
     */
    public static function errorMessage($valiData, $inputInfo = [], $opInfo = []) {
        static::$opInfo = $opInfo;
        static::$inputInfo = $inputInfo;

        $rules = Lev::getSettings($inputInfo['rules']);
        $settings = Lev::getSettings($inputInfo['settings']);
        foreach (static::$ruleSettings as $ruleKey => $msg) {
            $method = 'rule_'.$ruleKey;
            if (isset($settings[$method]) || isset($rules[0][$ruleKey])) {
                static::$method($valiData, $rules[0][$ruleKey]);
                if (static::$errorMsg) break;
            }
        }

    }

    public static function rule_must($valiData, $setval = null) {
        if (!$setval && !$valiData && !is_numeric($valiData)) {
            static::$errorMsg = Lev::responseMsg(-4044301, static::$ruleSettings['must'].'【'.static::$inputInfo['title'].'】');
        }
    }

    public static function rule_minLen($valiData, $setval = null) {
        if ($setval) {
            $len = static::countLength($valiData);
            if ($len < $setval) {
                static::$errorMsg = Lev::responseMsg(-4044302,
                    static::$ruleSettings['minLen'] . '【' . static::$inputInfo['title'] . '】' . '：' . $setval);
            }
        }
    }

    public static function rule_maxLen($valiData, $setval = null) {
        if ($setval) {
            $len = static::countLength($valiData);
            if ($len > $setval) {
                static::$errorMsg = Lev::responseMsg(-4044303,
                    static::$ruleSettings['maxLen'] . '【' . static::$inputInfo['title'] . '】' . '：' . $setval);
            }
        }
    }

    public static function rule_unique($valiData, $setval = null) {
        if (!$setval) {
            FormData::$uniques[static::$inputInfo['id']] = $md5 = substr(md5($valiData), 8, 16);//设置唯一字段值

            LevfmDatas::checkUnique(static::$inputInfo['id'], $md5, Lev::arrv('id', static::$opInfo, false), Lev::arrv('id', FormData::$formInfo, false)) &&
            static::$errorMsg = Lev::responseMsg(-4044304, static::$ruleSettings['unique'].'【'.static::$inputInfo['title'].'】');
        }
    }

    public static function rule_include($valiData, $setval = null) {
        if ($setval && $setval = Lev::explodev($setval, "\n")) {
            foreach ($setval as $v) {
                if (stripos($valiData, $v) !== false) {
                    static::$errorMsg = Lev::responseMsg(-4044305, static::$ruleSettings['include'].'【'.static::$inputInfo['title'].'】'.'：'.$v);
                    break;
                }
            }
        }
    }



    public static function setdataType() {
        return static::$dataTypes;
    }

    /**
     * 数据过滤、格式验证
     * @param $valiData
     * @param array $inputInfo
     * @return array|mixed|string
     */
    public static function dataType($valiData, $inputInfo = []) {
        if (in_array($inputInfo['inputtype'], ['wangeditor', 'htmlTextarea'])) {
            $valiData = Lev::decodeHtml(Lev::removeScript(Lev::decodeHtml($valiData)), false);
        }
        $rules = Lev::getSettings($inputInfo['rules']);
        if (!empty($rules[0]['dataType'])) {
            $method = 'check_'. $rules[0]['dataType'];
            $valiData = static::$method($valiData);
        }else {
            $valiData = Lev::stripTags($valiData);
        }

        if (stripos($inputInfo['inputtype'], 'textarea') === false && stripos($inputInfo['inputtype'], 'editor') === false) {
            static::check_quots($valiData) &&
            static::$errorMsg = Lev::responseMsg(-404444, '抱歉，禁止提交英文双引号【 " 】【' . $inputInfo['title'] . '】');
        }

        return $valiData;
    }

    public static function check_quots($valiData) {
        if (is_array($valiData)) {
            foreach ($valiData as $k => $v) {
                if (static::check_quots($v)) return true;
            }
        }else {
            return strpos($valiData, '"') !== false;
        }
        return false;
    }

    public static function check_floatval($valiData) {
        return floatval($valiData);
    }

    public static function check_intval($valiData) {
        return intval($valiData);
    }

    public static function check_url($valiData) {
        $valiData = Lev::stripTags($valiData);
        if (strpos($valiData, 'http://') !== 0 && strpos($valiData, 'https://') !== 0) {
            static::$errorMsg = Lev::responseMsg(-4044001, '抱歉，必须以http://或https://开头');
        }
        return $valiData;
    }

    public static function check_email($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        $len = strlen($valiData);
        if ($len >32 || $len <9) {
            static::$errorMsg = Lev::responseMsg(-4044002, '抱歉，邮箱Email长度应该在9~32个字符');
        }elseif (!static::checkEmail($valiData)) {
            static::$errorMsg = Lev::responseMsg(-4044003, '抱歉，邮箱Email不合法');
        }
        return $valiData;
    }

    public static function check_mobile($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        $len = strlen($valiData);
        if (!is_numeric($len) || $valiData[0] != 1 || $len != 11) {
            static::$errorMsg = Lev::responseMsg(-4044004, '抱歉，中国大陆手机号必须是11位数字且1开头');
        }
        return $valiData;
    }

    public static function check_ip($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        $arr = explode('.', $valiData);
        if (count($arr) != 4 || $arr[3] == 0 || $arr[3] == 255){
            static::$errorMsg = Lev::responseMsg(-4044005, '抱歉，IPv4地址不合法');
        }else {
            foreach ($arr as $v) {
                if ($v > 255 || $v < 0) {
                    static::$errorMsg = Lev::responseMsg(-4044006, '抱歉，IPv4地址不合法0~255');
                    break;
                }
            }
        }
        return $valiData;
    }

    public static function check_ipv6($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        $arr = explode(':', $valiData);
        if (count($arr) != 8) {
            static::$errorMsg = Lev::responseMsg(-4044007, '抱歉，IPv6地址不合法');
        }else {
            foreach ($arr as $v) {
                if (strlen($v) != 4 || !preg_match('/^[a-fA-F0-9][a-fA-F0-9]+$/', $v)) {
                    static::$errorMsg = Lev::responseMsg(-4044008, '抱歉，IPv6地址不合法0000~FFFF');
                    break;
                }
            }
        }
        return $valiData;
    }

    public static function check_letter($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        if (!preg_match('/^[a-zA-Z][a-zA-Z]+$/', $valiData)) {
            static::$errorMsg = Lev::responseMsg(-4044009, '抱歉，仅限字母组合');
        }
        return $valiData;
    }

    public static function check_letters($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        if (!preg_match('/^[a-zA-Z0-9][a-zA-Z0-9]+$/', $valiData)) {
            static::$errorMsg = Lev::responseMsg(-4044010, '抱歉，仅限字母、数字组合');
        }
        return $valiData;
    }

    public static function check_letters2($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        if (!preg_match('/^[a-zA-Z][a-zA-Z0-9\_]+$/', $valiData)) {
            static::$errorMsg = Lev::responseMsg(-4044011, '抱歉，只允许字母、数字和下划线，必须以字母开头');
        }
        return $valiData;
    }

    public static function check_letters3($valiData) {
        $valiData = strtolower(Lev::stripTags($valiData));
        if (!preg_match('/^[a-zA-Z0-9\-_][a-zA-Z0-9\-_.]+$/', $valiData)) {
            static::$errorMsg = Lev::responseMsg(-4044012, '抱歉，只允许字母、数字、中划线和下划线，不允许点【.】开头');
        }
        return $valiData;
    }



    public static function checkEmail($email)
    {
        if (strpos($email, '@') === false || strpos($email, '..') !== false || strpos($email, '.@') !== false) {
            return false;
        }
        $arr = explode('@', $email);
        if (!$arr[1] || isset($arr[2]) || !strpos($arr[1], '.')) {
            return false;
        }
        return preg_match('/^[a-z0-9_][a-z0-9_\-.@]+$/', $email);
    }

    public static function getSettingRuleKey($setKey)
    {
        return strpos($setKey, 'rule_') === 0 ? substr($setKey, 5) : '';
    }

    private static function countLength($string) {
        if (is_array($string)) {
            return count($string);
        }elseif (inputsFormWidget::isNumberInput(static::$inputInfo)) {
            $len = strlen($string);
            return $len > $string ? $len : $string;
        }
        return strlen($string);
    }


}